package com.lkd.controller;

import com.lkd.dto.SkuDto;
import com.lkd.entity.Sku;
import com.lkd.entity.SkuClass;
import com.lkd.service.ISkuService;
import com.lkd.utils.AliOssUtil;
import com.lkd.vo.PageBean;
import com.lkd.vo.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@RestController
@RequiredArgsConstructor
public class SkuController {

    private final ISkuService skuService;

    /**
     * 上传文件
     * @param fileName
     * @return
     */
    @Autowired
    private AliOssUtil ossUtil;

    /**
     * 文件上传
     */
    @PostMapping("/api/vm-service/sku/fileUpload")
    public Result upload(@RequestBody MultipartFile fileName) throws Exception {
        log.info("文件上传开始：{}", fileName.getOriginalFilename());
        //获取原始文件后缀名
        String originalFilename = fileName.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新的文件名
        String objectName = UUID.randomUUID().toString() + suffixName;
        InputStream inputStream = fileName.getInputStream();
        String url = ossUtil.upload(objectName, inputStream);
        return Result.success(url);
    }

    /**
     * 新增商品
     * @param sku
     * @return
     */
    @PostMapping("/api/vm-service/sku")
    public Boolean save(@RequestBody  Sku sku) {
        // 调用 MyBatis-Plus 的 save 方法，其返回值是 boolean 类型，表示是否成功
        boolean isSaved = skuService.save(sku);
        // 根据数据库操作的实际结果返回，而不是想当然地返回 true
        return isSaved;
    }

    /**
     * 分页查询
     * @param skuDto
     * @return
     */
    @GetMapping("/api/vm-service/sku/search")
    public Result search(SkuDto skuDto) {
        PageBean<Sku> pageBean = skuService.search(skuDto);
        return Result.success(pageBean);

    }

    @PutMapping("/api/vm-service/sku")
    public Result update(@RequestBody Sku sku) {
        skuService.updateById(sku);
        return Result.success();
    }


}
